#import "ShopListController.h"
#import "DetailShopViewController.h"
#import "Supplier.h"
#import "SupplierCategory.h"
#import "PublicFunction.h"
#import "UICustomImageView.h"
#import "Constants.h"
#import "FMDBTransactionHistory.h"
#import "MobClick.h"
#import "SupplierManager.h"


@interface ShopListController (private)
- (void)refresh;
- (void)stopLoading;
- (void)startLoading;
@end
@implementation ShopListController
@synthesize manager;
@synthesize suppliers;
@synthesize currentPage;
@synthesize usingPickerView;
@synthesize addBtn;
@synthesize typeBtn;	
@synthesize timeBtn;
@synthesize tiaoImageView;
@synthesize submitButton;
@synthesize cancelButton;
@synthesize tableViews;
@synthesize appDelegate;
@synthesize _refreshHeaderView;
@synthesize _reloading;
@synthesize HUD;
@synthesize road;
@synthesize isSelling;
@synthesize isTouched;
@synthesize typePickerView;
@synthesize addressPickerView;
@synthesize shopHoursPickerView;
@synthesize addressTestData;
@synthesize shopHoursTestData;
@synthesize typeTestData;
@synthesize tempSupId;
@synthesize tempSupName;
@synthesize tempSupplierCategoryName;
@synthesize fSuppliers;
@synthesize sSuppliers;


#define addressTag 1//地址按钮标签
#define typeTag 2//类型按钮标签
#define shopHoursTag 3//营业时间标签

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

//用代码添加addressPickerView控件,初始位置在屏幕外
-(void) addAddressPickerView {
    if(addressPickerView==nil){
        addressPickerView=[[UIPickerView alloc] initWithFrame:CGRectMake(0,460,320,460)];
		addressPickerView.delegate = self;
		addressPickerView.dataSource = self;
		addressPickerView.showsSelectionIndicator = YES;
    }
    [self.view addSubview:addressPickerView];
}

//用代码添加typePickerView控件,初始位置在屏幕外
-(void) addTypePickerView {
    if(typePickerView==nil){
		typePickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 460, 320, 460)];
		typePickerView.delegate = self;
		typePickerView.dataSource = self;
		typePickerView.showsSelectionIndicator = YES;
    }
    [self.view addSubview:typePickerView];
}

//用代码添加shopHoursPickerView控件,初始位置在屏幕外
-(void) addShopHoursPickerView {
    if(shopHoursPickerView==nil){
		shopHoursPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 460, 320, 460)];
		shopHoursPickerView.delegate = self;
		shopHoursPickerView.dataSource = self;
		shopHoursPickerView.showsSelectionIndicator = YES;
    }
    [self.view addSubview:shopHoursPickerView];
}

//初始化导航栏
-(void)initNav{
    //定义导航栏左侧按钮
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 54, 27)];
    
    NSString *filePath2=[[NSBundle mainBundle] pathForResource:@"navLeftBtn" ofType:@"png"];
    [leftButton setBackgroundImage:[UIImage imageWithContentsOfFile:filePath2] forState:UIControlStateNormal];
    [leftButton setTitle:@"首 页" forState:UIControlStateNormal]; 
    //内容1
    leftButton.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:14]; 
    [leftButton addTarget:self action:@selector(backButtonPressdDelay:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftItem;
}
//后退手势
-(void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer{
    if(recognizer.direction==UISwipeGestureRecognizerDirectionRight) {
        [self.navigationController popViewControllerAnimated:YES];
        //执行程序
    }
}

- (void)backButtonPressdDelay:(id)sender{
    NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
    SystemSoundID system_sound_id;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
    AudioServicesPlaySystemSound(system_sound_id);
    [self performSelector:@selector(backButtonPressd:) withObject:sender afterDelay:0.1];
}

- (void)backButtonPressd:(id)sender{
    if(isTouched){
        isTouched=NO;
    //将当前视图推出栈，程序将进入上一视图
    [self.navigationController popViewControllerAnimated:YES];
}
}

//初始化选择条件按钮
-(void)initTypeBtn{
    //按钮区域背景
    UIImageView* bnView=[[UIImageView alloc] initWithFrame:CGRectMake(0,-5,320,50)];    
    NSString *filePath=[[NSBundle mainBundle] pathForResource:@"shopBtnBg" ofType:@"png"];
    [bnView setImage:[UIImage imageWithContentsOfFile:filePath]];
    [self.view addSubview:bnView];
    //初始化按钮    
    addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addBtn.frame = CGRectMake(5, 5, 100, 30);
    addBtn.tag=1;
    [addBtn setTitle:@"周边地区" forState:UIControlStateNormal];
    //设置文字居左，默认居中
    //    addBtn.contentHorizontalAlignment =UIControlContentHorizontalAlignmentLeft;
    //详细设置文字位置，（上，左，下，右），初始值为居中左边
    [addBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -15, 0, 0)];
    NSString *filePath2=[[NSBundle mainBundle] pathForResource:@"shopTypeButton" ofType:@"png"];
    [addBtn setBackgroundImage:[UIImage imageWithContentsOfFile:filePath2] forState:UIControlStateNormal];
    //标题2
    addBtn.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:16]; 
    [addBtn addTarget:self action:@selector(showPickerViewAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:addBtn];
    
    typeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    typeBtn.frame = CGRectMake(110, 5, 100, 30);
    typeBtn.tag=2;
    
    int tempId=[appDelegate.supId intValue];
    switch (tempId)
    {
        case 30:
        {
            [typeBtn setTitle:@"中式快餐" forState:UIControlStateNormal]; 
        }
            break;
        case 31:
        {
            [typeBtn setTitle:@"西式快餐" forState:UIControlStateNormal]; 
        }
            break;
        case 32:
        {
            [typeBtn setTitle:@"茶餐厅" forState:UIControlStateNormal]; 
        }
            break;
        case 33:
        {
            [typeBtn setTitle:@"粥面类" forState:UIControlStateNormal]; 
        }
            break;
        case 34:
        {
            [typeBtn setTitle:@"小吃" forState:UIControlStateNormal]; 
        }
            break;
        case 42:
        {
            [typeBtn setTitle:@"餐厅大排档" forState:UIControlStateNormal]; 
        }
            break;
        case 43:
        {
            [typeBtn setTitle:@"烤鱼烧烤" forState:UIControlStateNormal]; 
        }
            break;
        case 44:
        {
            [typeBtn setTitle:@"冷饮甜品" forState:UIControlStateNormal]; 
        }
            break;
    }
    tempSupplierCategoryName = [typeBtn titleForState:UIControlStateNormal];
    //详细设置文字位置，（上，左，下，右），初始值为居中左边
    [typeBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -15, 0, 0)];
    [typeBtn setBackgroundImage:[UIImage imageWithContentsOfFile:filePath2] forState:UIControlStateNormal];
    typeBtn.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:16]; 
    [typeBtn addTarget:self action:@selector(showPickerViewAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:typeBtn];
    
    timeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    timeBtn.frame = CGRectMake(215, 5, 100, 30);
    timeBtn.tag=3;
    [timeBtn setTitle:@"营业情况" forState:UIControlStateNormal];
    //详细设置文字位置，（上，左，下，右），初始值为居中左边
    [timeBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -15, 0, 0)];
    [timeBtn setBackgroundImage:[UIImage imageWithContentsOfFile:filePath2] forState:UIControlStateNormal];
    timeBtn.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:16]; 
    [timeBtn addTarget:self action:@selector(showPickerViewAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:timeBtn];
}

//初始化picker样式
-(void)initPickers{
    //隐藏pickerView上的横条和确定取消按钮
    if(tiaoImageView==nil){
        tiaoImageView=[[UIImageView alloc]init];
    }
    
    NSString *filePath1=[[NSBundle mainBundle] pathForResource:@"pickerBg" ofType:@"png"];
    [tiaoImageView setImage:[UIImage imageWithContentsOfFile:filePath1]];
    [self.view addSubview:tiaoImageView];
    [tiaoImageView setHidden: YES];
    
    submitButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [submitButton setTitle:@"确定" forState:UIControlStateNormal];
    [submitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    NSString *filePath2=[[NSBundle mainBundle] pathForResource:@"cancelBtnBg" ofType:@"png"];
    [submitButton setBackgroundImage:[UIImage imageWithContentsOfFile:filePath2] forState:UIControlStateNormal];
    [submitButton addTarget:self action:@selector(pickerEndButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:submitButton];
    [submitButton setHidden:YES];
    
    cancelButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [cancelButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [cancelButton setBackgroundImage:[UIImage imageWithContentsOfFile:filePath2] forState:UIControlStateNormal];
    [cancelButton addTarget:self action:@selector(pickerCancelButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:cancelButton];
    [cancelButton setHidden:YES];
}

//- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
//    //tag为1时为点击拨号按钮时弹出的对话框
//    if(alertView.tag == 1){
//        //将当前视图推出栈，程序将进入上一视图
//        [self.navigationController popViewControllerAnimated:YES];
//    }
//}


- (void)firstLoad {
    
//    @autoreleasepool
//    {
    suppliers = [manager getSupplier:appDelegate.supId pageIndex:1 road:nil isSelling:nil];
//    Supplier *sss=[[Supplier alloc]init];
//    sss.supplierName
    //订单组
    fSuppliers=[[NSMutableArray alloc]init];
    //非订单组
    sSuppliers=[[NSMutableArray alloc]init];
    for(Supplier *supplier in suppliers){
        if([supplier.supplierName isEqualToString:@"美味快餐厅"]){
            [sSuppliers addObject:supplier];
        }
        else{
            [fSuppliers addObject:supplier];
        }
    }
    for(Supplier *supplier in fSuppliers){
        NSLog(@"订单组%@",supplier.supplierName);
    }
    
    for(Supplier *supplier in sSuppliers){
        NSLog(@"非订单组%@",supplier.supplierName);
    }
    
//    for(Supplier *supplier in suppliers){
//        NSLog(@"订单组%@",supplier.supplierName);
//    }
    
    
    
//    }
    
//    if([appDelegate status])
//    {
//        suppliers = [[manager getSupplier:appDelegate.supId pageIndex:1 road:nil isSelling:nil] retain];  
        //联网，添加到本地
//        [fmdbSupplierManager insertSupplierByCategoryId:suppliers supplierCategoryId:appDelegate.supId sPage:@"1"];
//    }
//    else{
//        suppliers= [[fmdbSupplierManager getSupplierByCategoryIdAndPageFromLoc:appDelegate.supId sPage:@"1" road:nil isSelling:nil] retain];
//    }
//    
//    //商铺列表
//    tableViews=[[UITableView alloc] initWithFrame:CGRectMake(0, 45, 320, 325)]; 
//    tableViews.hidden=YES;
//    //    tableViews.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleHeight;  
//    tableViews.backgroundColor=[UIColor whiteColor];  
//    tableViews.delegate=self;  
//    tableViews.dataSource=self;    
//    tableViews.contentSize =CGSizeMake(320, [suppliers count]*64);
//    //减慢tableview的滚动速度，正常值为1.f
//    tableViews.decelerationRate=0.1f;
//
//    //    //隐藏tableview滚动条
//    //    tableViews.showsVerticalScrollIndicator=NO;  
//    //  设置tableview滚动条在左边显示
//    //    tableViews.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 0, tableViews.bounds.size.width-7);
//    //添加到view窗体上  
//    [self.view addSubview:tableViews];


    
    if([suppliers count]==0||suppliers==nil){
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"网络不稳定请重试" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        alertView.tag=2;
        [alertView show];
    }
    else{
    //初始化页数
    currentPage = 1;
    //导入数据
    if(addressTestData==nil){
        addressTestData = [[NSArray alloc] initWithObjects:@"周边地区",@"市政府", @"步行街",@"狮标",@"鸳鸯池",@"华侨医院",@"服装城", nil];
        shopHoursTestData = [[NSArray alloc] initWithObjects:@"营业情况",@"营业中", @"打烊", nil];
        typeTestData=[[NSMutableArray alloc]initWithObjects:@"类型",nil];
        NSArray *supplierCategoriess = [recieveDictionary objectForKey:@"SupplierCategories"];
        for(SupplierCategory *supplierCategory in supplierCategoriess){
            [typeTestData addObject:supplierCategory.supplierCategoryName];
        }
    }

        //统计菜系点击次数到友盟
        NSString *source = (NSString *)[recieveDictionary objectForKey:@"source"];
        if(source == @"mainPageSupType"){
            NSString *supTypeName = (NSString *)[recieveDictionary objectForKey:@"supTypeName"];
            [MobClick event:(NSString *)@"mainPageSupType" label:(NSString *)supTypeName];
        }
    
    if([suppliers count]>=SSsupplierCount){
        [tableViews reloadData];
        [_refreshHeaderView removeFromSuperview];
        _refreshHeaderView.frame=CGRectMake(0, tableViews.contentSize.height, 320, 250);
        [tableViews addSubview:_refreshHeaderView];
        //        [_refreshHeaderView release];
        [_refreshHeaderView refreshLastUpdatedDate];
    }
    else{
        [tableViews reloadData];
        _refreshHeaderView.frame=CGRectMake(0, 600, 320, 250);
    }
    
    }
}

-(void)changeType{
    suppliers = [manager getSupplier:appDelegate.supId pageIndex:currentPage road:road isSelling:isSelling];
    
    
    for(Supplier *supplier in suppliers){
        if([supplier.supplierName isEqualToString:@"美味快餐厅"]){
            [sSuppliers addObject:supplier];
        }
        else{
            [fSuppliers addObject:supplier];
        }
    }
    for(Supplier *supplier in fSuppliers){
        NSLog(@"订单组%@",supplier.supplierName);
    }
    
    for(Supplier *supplier in sSuppliers){
        NSLog(@"非订单组%@",supplier.supplierName);
    }
    
//    if([appDelegate status]){
//        suppliers = [[manager getSupplier:appDelegate.supId pageIndex:currentPage road:road isSelling:isSelling] retain];
        //添加到本地
//        [fmdbSupplierManager insertSupplierByCategoryId:suppliers supplierCategoryId:appDelegate.supId sPage:currentPageString];
//    }
//    else{
//        
//        //离线
//        suppliers=[[fmdbSupplierManager getSupplierByCategoryIdAndPageFromLoc:appDelegate.supId sPage:@"1" road:road isSelling:isSelling] retain];
//    }
    if (suppliers.count==0) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"没有该类型的商家" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
    }
    
    
    //统计用户搜索时的三个条件数据到友盟
    [MobClick event:@"shopListSearchConditionsNew" label:(NSString *)[[NSString alloc]initWithFormat:@"地区：%@ 类型：%@ 营业情况：%@",road?road:@"未选择",tempSupplierCategoryName?tempSupplierCategoryName:@"未选择",isSelling?isSelling:@"未选择"]];
    
    if([suppliers count]>=SSsupplierCount){
        [tableViews scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO]; 
        [tableViews reloadData];
        [_refreshHeaderView removeFromSuperview];
        _refreshHeaderView.frame=CGRectMake(0, tableViews.contentSize.height, 320, 250);
        [tableViews addSubview:_refreshHeaderView];
//        [_refreshHeaderView release];
        [_refreshHeaderView refreshLastUpdatedDate];
    }
    else{
        [tableViews reloadData];
        _refreshHeaderView.frame=CGRectMake(0, 600, 320, 250);
    }
    
    
    
//    tableViews.contentSize =CGSizeMake(320, [suppliers count]*64);
//    if([suppliers count]>=5){
//        _refreshHeaderView.frame=CGRectMake(0, tableViews.contentSize.height, 320, 480);
//        [_refreshHeaderView refreshLastUpdatedDate];
//        
//    }
//    [tableViews reloadData];
}


-(void)showHUD:(NSString *)type{
    if(type==nil)
        //初次加载
    {
        [HUD showWhileExecuting:@selector(firstLoad)onTarget:self withObject:Nil animated:YES];
    }
    if(type==@"condition")
    {
        [HUD showWhileExecuting:@selector(changeType) onTarget:self withObject:nil animated:YES];
    }
}

//点击完成触发：
-(IBAction)pickerEndButtonPress:(id)sender
{
    NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
    SystemSoundID system_sound_id;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
    AudioServicesPlaySystemSound(system_sound_id);
    
    NSArray *supplierCategories = [recieveDictionary objectForKey:@"SupplierCategories"];
    if(usingPickerView == @"addressPicker")
    {
        NSInteger rows = [addressPickerView selectedRowInComponent:0];
        NSString *strs = [[NSString alloc] initWithFormat:@"%@",[addressTestData objectAtIndex:rows]];
        [addBtn setTitle:strs forState:UIControlStateNormal];
        [addBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -20, 0, 0)];
    }
    else if(usingPickerView == @"typePicker")
    {
        NSInteger rows = [typePickerView selectedRowInComponent:0];
        NSString *strs = [[NSString alloc]initWithFormat:@"%@",[typeTestData objectAtIndex:rows]];
        [typeBtn setTitle:strs forState:UIControlStateNormal];
        [typeBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -20, 0, 0)];
        if(rows==0){
            appDelegate.supId=nil;
            tempSupplierCategoryName = nil;
        }
        else{
            SupplierCategory *supplierCategory=[supplierCategories objectAtIndex:rows-1];
            appDelegate.supId=[NSString stringWithFormat: @"%d", supplierCategory.supplierCategoryId];
            tempSupplierCategoryName = strs;
        }
    }
    else if(usingPickerView == @"shopHoursPicker")
    {
        NSInteger rows = [shopHoursPickerView selectedRowInComponent:0];
        NSString *strs = [[NSString alloc]initWithFormat:@"%@",[shopHoursTestData objectAtIndex:rows]];
        [timeBtn setTitle:strs forState:UIControlStateNormal];
        [timeBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -20, 0, 0)];
    }
    //点击完成时显示第一页
    currentPage = 1;
    road = addBtn.titleLabel.text;
    isSelling = @"";
    if([road isEqualToString: @"周边地区"]){
        road = nil;
    }
    if([timeBtn.titleLabel.text isEqualToString: @"营业中"]){
        isSelling = @"y";
    }
    else if([timeBtn.titleLabel.text isEqualToString: @"打烊"]){
        isSelling = @"n";
    }
    else{
        isSelling = nil;
    }
//    currentPageString=[[NSString alloc] initWithFormat: @"%d", currentPage];
    addBtn.enabled=YES;
    typeBtn.enabled=YES;
    timeBtn.enabled=YES;
    [self hiddenPickerView];
    [self showHUD:@"condition"];

}

//点击取消触发
-(IBAction)pickerCancelButtonPress:(id)sender
{
    NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
    SystemSoundID system_sound_id;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
    AudioServicesPlaySystemSound(system_sound_id);
    [self hiddenPickerView];
    addBtn.enabled=YES;
    typeBtn.enabled=YES;
    timeBtn.enabled=YES;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    //添加手势
    UISwipeGestureRecognizer *recognizer; 
    recognizer = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeFrom:)];
    [recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
    [[self view] addGestureRecognizer:recognizer];
    self.navigationController.navigationBarHidden = NO;
    
    //初始化刷新cell
    _refreshHeaderView=[[EGORefreshTableHeaderView alloc] init];
    _refreshHeaderView.delegate=self;
    
    //初始化hud
    HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
    [self.navigationController.view addSubview:HUD];
	HUD.dimBackground = YES;
    HUD.delegate=self;
    //初始化本地商铺管理
//    if(fmdbSupplierManager==nil){
//        fmdbSupplierManager=[[FMDBSupplierManager alloc]init];
//    }
    //初始化商铺管理
    manager = [[SupplierManager alloc] init];

    //初始化appDelegate
    appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    //设置视图title
    self.title=@"商家列表";
    //初始化导航栏
    [self initNav];
    
    //商铺列表
    tableViews=[[UITableView alloc] initWithFrame:CGRectMake(0, 45, 320, SSsupplierListH)];
//    tableViews.hidden=YES;
    //    tableViews.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleHeight;  
    tableViews.backgroundColor=[UIColor whiteColor];  
    tableViews.delegate=self;  
    tableViews.dataSource=self;    
    tableViews.contentSize =CGSizeMake(320, [suppliers count]*64);
    //减慢tableview的滚动速度，正常值为1.f
    tableViews.decelerationRate=0.1f;
    
    
    
    
    //    //隐藏tableview滚动条
    //    tableViews.showsVerticalScrollIndicator=NO;  
    //  设置tableview滚动条在左边显示
    //    tableViews.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 0, tableViews.bounds.size.width-7);
    //添加到view窗体上  
    [self.view addSubview:tableViews];
    //初始化选择条件按钮
    [self initTypeBtn];
    //初始化picker
    [self initPickers];
    
    [self showHUD:nil];

}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:NO];
    isTouched=YES;
}


/**************************/ 
/*       商家列表视图       */
/*************************/

//返回表试图分区行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [suppliers count];
}

//设置表试图每行显示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSInteger index=indexPath.row;
    Supplier *supplier=[suppliers objectAtIndex:index];
    static NSString *CellIdentifier = @"CustomCell";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    
	if(cell == nil) {
		cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    cell.opaque=YES;
    
//    if(supplier.supplierId==236&&tempBool){
//        UICustomImageView *imageView = (UICustomImageView *)[cell.contentView viewWithTag:100];
//        if (imageView == nil) {
//            imageView = [[UICustomImageView alloc] initWithFrame:CGRectMake(8, 2, 60, 60)];
//            imageView.opaque=YES;
//            [imageView setContentMode:UIViewContentModeScaleAspectFit];
//            [imageView setUserInteractionEnabled:NO];
//            [imageView setTag:100];
//            [cell.contentView addSubview:imageView];
//            
//        }
//        [imageView setImage:nil];
//        [imageView setImageURL:supplier.imgUrl];
//        tempInt=1;
//    }
//    else{
    
    UICustomImageView *imageView = (UICustomImageView *)[cell.contentView viewWithTag:100];
    if (imageView == nil) {     
        imageView = [[UICustomImageView alloc] initWithFrame:CGRectMake(8, 2, 60, 60)];
        imageView.opaque=YES;
        [imageView setContentMode:UIViewContentModeScaleAspectFit];
        [imageView setUserInteractionEnabled:NO];
        [imageView setTag:100];
        [cell.contentView addSubview:imageView];

    }
    [imageView setImage:nil];
    [imageView setImageURL:supplier.imgUrl];
    
    UILabel *shopNameLabel = (UILabel *)[cell.contentView viewWithTag:200];
    if (shopNameLabel == nil) {
        //标题2
        shopNameLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:16];
        shopNameLabel.opaque=YES;
        shopNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(85, 5, 220, 16)];
        //自定义颜色
        [shopNameLabel setTextColor:[UIColor colorWithRed:255.0/255.0 green:111.0/255.0 blue:6.0/255.0 alpha:1.0f]];
        [shopNameLabel setText:supplier.supplierName];
        shopNameLabel.tag = 200;
        [cell.contentView addSubview:shopNameLabel];

    }
    [shopNameLabel setText:supplier.supplierName];
    
    UILabel *shopTypeLable=(UILabel *)[cell.contentView viewWithTag:202];
    if (shopTypeLable == nil) {
        shopTypeLable = [[UILabel alloc] initWithFrame:CGRectMake(80, 30, 160, 12)];
        shopTypeLable.opaque=YES;
        shopTypeLable.font=[UIFont fontWithName:@"Helvetica" size:12];
        shopTypeLable.tag = 202;
        [cell.contentView addSubview:shopTypeLable];

    }
//    NSString *supplierCategoryName = [NSString stringWithFormat:@"【%@】",supplier.supplierCategoryName];
    NSString *supplierCategoryName = [[NSString alloc] initWithFormat:@"【%@】",supplier.supplierCategoryName];
    [shopTypeLable setText:supplierCategoryName];

    
    UILabel *shopAvgPriceLable=(UILabel *)[cell.contentView viewWithTag:203];
    if (shopAvgPriceLable == nil) {
        shopAvgPriceLable = [[UILabel alloc] initWithFrame:CGRectMake(165, 30, 100, 12)];
        shopAvgPriceLable.opaque=YES;
        shopAvgPriceLable.font=[UIFont fontWithName:@"Helvetica" size:12];
        //自定义颜色
        [shopAvgPriceLable setTextColor:[UIColor colorWithRed:255.0/255.0 green:111.0/255.0 blue:6.0/255.0 alpha:1.0f]];
//        [shopAvgPriceLable setBackgroundColor:[UIColor clearColor]];
        shopAvgPriceLable.tag = 203;
        [cell.contentView addSubview:shopAvgPriceLable];

    }
    NSString *avgPrice=[[NSString alloc]initWithFormat:@"人均: %.2f",supplier.avgPrice];
    [shopAvgPriceLable setText:avgPrice];

    
    UILabel *shopAddressLabel = (UILabel *)[cell.contentView viewWithTag:201];
    if (shopAddressLabel == nil) {
        shopAddressLabel = [[UILabel alloc] initWithFrame:CGRectMake(85, 48, 160, 12)];
        shopAddressLabel.opaque=YES;
        shopAddressLabel.font=[UIFont fontWithName:@"Helvetica" size:12];
//        [shopAddressLabel setBackgroundColor:[UIColor clearColor]];
        shopAddressLabel.tag = 201;
        [cell.contentView addSubview:shopAddressLabel];

    }
    NSString *tempAddress=[[NSString alloc]initWithFormat:@"地址: %@",supplier.address]; 
    [shopAddressLabel setText:tempAddress];

    
    UIButton *phoneButton = (UIButton *)[cell.contentView viewWithTag:300];
    if (phoneButton == nil) 
    {
        phoneButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
        phoneButton.opaque=YES;
        [phoneButton setFrame:CGRectMake(240, 27, 30, 30)];
        UIImage *image = [UIImage imageNamed:@"phoneImg.png"]; 
        [phoneButton setBackgroundImage:image forState:UIControlStateNormal]; 
        phoneButton.tag = 300;
        [phoneButton addTarget:self action:@selector(callAction:event:) forControlEvents:UIControlEventTouchUpInside];
        [cell.contentView addSubview:phoneButton];
        //点击拨号按钮直接拨号
    }
        [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
        cell.tag = supplier.supplierId;
//    }
    [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
    //设置cell的样式，带箭头
    
    return cell;
}

//定义点击拨号按钮时的操作 
- (void)callAction:(id)sender event:(id)event{ 
    NSSet *touches = [event allTouches]; 
//    NSSet *touches = [event allTouches]; 
//    UITouch *touch = [touches anyObject]; 
//    CGPoint currentTouchPosition = [touch locationInView:tableViews]; 
//    NSIndexPath *indexPath = [tableViews indexPathForRowAtPoint: currentTouchPosition]; 
//    if (indexPath == nil) { 
//        return; 
//    } 
//    NSUInteger  row = [indexPath row]; 
//    Supplier *rowData = [suppliers objectAtIndex:row]; 
//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"拨打电话" message:@"请选择要拨打的号码" delegate:self cancelButtonTitle:@"取  消" otherButtonTitles:nil];
//    if(rowData.phone.length != 0){
//        [alert addButtonWithTitle:rowData.phone];
//    }
//    if(rowData.phone2.length != 0){
//        [alert addButtonWithTitle:rowData.phone2];
//    }
//    if(rowData.telephone.length != 0){
//        [alert addButtonWithTitle:rowData.telephone];
//    }
//    if(rowData.telephone2.length != 0){
//        [alert addButtonWithTitle:rowData.telephone2];
//    } 
//    alert.tag = 1;
//	[alert show];
//	[alert release];
//    [self performSelectorOnMainThread:@selector(onResponseInMainThread) withObject:nil waitUntilDone:YES];
    
    NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
    SystemSoundID system_sound_id;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
    AudioServicesPlaySystemSound(system_sound_id);
    
    UITouch *touch = [touches anyObject]; 
    CGPoint currentTouchPosition = [touch locationInView:tableViews]; 
    NSIndexPath *indexPath = [tableViews indexPathForRowAtPoint: currentTouchPosition]; 
    if (indexPath == nil) { 
        return; 
    } 
    NSUInteger  row = [indexPath row]; 
    Supplier *rowData = [suppliers objectAtIndex:row]; 
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"拨打电话" message:@"请选择要拨打的号码" delegate:self cancelButtonTitle:@"取  消" otherButtonTitles:nil];
    if(rowData.phone.length != 0){
        [alert addButtonWithTitle:rowData.phone];
    }
    if(rowData.phone2.length != 0){
        [alert addButtonWithTitle:rowData.phone2];
    }
    if(rowData.telephone.length != 0){
        [alert addButtonWithTitle:rowData.telephone];
    }
    if(rowData.telephone2.length != 0){
        [alert addButtonWithTitle:rowData.telephone2];
    } 
    alert.tag = 1;
    //点击拨号按钮时，将当前行的商家ID和商家NAME保存到变量中
    tempSupId = [[NSString alloc] initWithFormat:@"%d",rowData.supplierId];
    tempSupName = rowData.supplierName;
	[alert show];

}
//-(void)onResponseInMainThread{
//    NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
//    SystemSoundID system_sound_id;
//    AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
//    AudioServicesPlaySystemSound(system_sound_id);
//    
//    UITouch *touch = [touches anyObject]; 
//    CGPoint currentTouchPosition = [touch locationInView:tableViews]; 
//    NSIndexPath *indexPath = [tableViews indexPathForRowAtPoint: currentTouchPosition]; 
//    if (indexPath == nil) { 
//        return; 
//    } 
//    NSUInteger  row = [indexPath row]; 
//    Supplier *rowData = [suppliers objectAtIndex:row]; 
//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"拨打电话" message:@"请选择要拨打的号码" delegate:self cancelButtonTitle:@"取  消" otherButtonTitles:nil];
//    if(rowData.phone.length != 0){
//        [alert addButtonWithTitle:rowData.phone];
//    }
//    if(rowData.phone2.length != 0){
//        [alert addButtonWithTitle:rowData.phone2];
//    }
//    if(rowData.telephone.length != 0){
//        [alert addButtonWithTitle:rowData.telephone];
//    }
//    if(rowData.telephone2.length != 0){
//        [alert addButtonWithTitle:rowData.telephone2];
//    } 
//    alert.tag = 1;
//	[alert show];
//
//}

//根据被点击按钮的索引处理点击事件  
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    //tag为1时为点击拨号按钮时弹出的对话框
    if(alertView.tag == 1){
        NSString *number = [alertView buttonTitleAtIndex:buttonIndex];
        //phoneNumber为号码字符串 
        NSString *phoneNumber = [[NSString alloc] initWithFormat:@"tel://%@",number];
        //统计拨打电话的次数到友盟
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                              tempSupId,@"商家ID",tempSupName,@"商家名称", nil];
        [MobClick event:@"shopCallActionNew" attributes:dict];
        //拨号 
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]]; 

    }
    //网络不通，返回上页
    if(alertView.tag==2){
                //将当前视图推出栈，程序将进入上一视图
                [self.navigationController popViewControllerAnimated:YES];
    }
}

//选中Cell响应事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(isTouched){
        isTouched=NO;
        
        NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
        SystemSoundID system_sound_id;
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
        AudioServicesPlaySystemSound(system_sound_id);
    [tableView deselectRowAtIndexPath:indexPath animated:YES];//选中后的反显颜色即刻消失
    //无点击picker确定，跳转页面，隐藏picker
    [self hiddenPickerView];
    __strong NSString *supplierId = [[NSString alloc] initWithFormat:@"%d",[tableView cellForRowAtIndexPath:indexPath].tag];  
    //创建新的试图并将试图推入栈中
    DetailShopViewController *detailShopViewController = [[DetailShopViewController alloc]init];
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity :1];
    [dictionary setObject:supplierId forKey:@"supId"]; 
    [dictionary setObject:@"shopListCellSelectedNew" forKey:@"source"];//用户统计到友盟时的来源判断
    [detailShopViewController setRecieveDictionary:dictionary];
    [self.navigationController pushViewController: detailShopViewController animated:YES];
}
}

//设置表试图行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath   
{
    return 64;
}

/************************/ 
/*     索搜类型选取器      */
/************************/
//显示地区选取器
-(void) showAddressPickerView {
    [self addAddressPickerView];
    //将所有选取器和横条都隐藏
    [self hiddenPickerView];
    /************************/ 
    /*     选取器动画效果      */
    /************************/
    //显示地区选取器，隐藏其他
    //开始动画
    [UIView beginAnimations: @"Animation" context:nil];
    //设定动画持续时间
    [UIView setAnimationDuration:0.3]; 
    //生成选取器，并向上拉动
    if(SSiphoneType==0){
        addressPickerView.frame = CGRectMake(0, 190, 320, 200);
        tiaoImageView.frame = CGRectMake(0, 162, 320, 37);
        submitButton.frame = CGRectMake(267, 165, 48, 25);
        cancelButton.frame = CGRectMake(7, 165, 48, 25);
    }
    if(SSiphoneType==1){
    addressPickerView.frame = CGRectMake(0, 190+IOS5HEIGHT, 320, 200);
    tiaoImageView.frame = CGRectMake(0, 162+IOS5HEIGHT, 320, 37);
    submitButton.frame = CGRectMake(267, 165+IOS5HEIGHT, 48, 25);
    cancelButton.frame = CGRectMake(7, 165+IOS5HEIGHT, 48, 25);
    }
    //动画结束
    [UIView commitAnimations]; 
    [addressPickerView setHidden:NO];
    //显示确定和取消按钮的横条
    [submitButton setHidden:NO];
    [cancelButton setHidden:NO];
    [tiaoImageView setHidden:NO];
}

//显示类型选取器
-(void) showTypePickerView {
    [self addTypePickerView];
    //将所有选取器和横条都隐藏
    [self hiddenPickerView];
    //显示类型选取器
    [UIView beginAnimations: @"Animation" context:nil];
    [UIView setAnimationDuration:0.3];
        if(SSiphoneType==0){
    typePickerView.frame = CGRectMake(0, 190, 320, 200);
    submitButton.frame = CGRectMake(267, 165, 48, 25);
    cancelButton.frame = CGRectMake(7, 165, 48, 25);
    tiaoImageView.frame = CGRectMake(0, 162, 320, 37);
        }
    if(SSiphoneType==1){
        typePickerView.frame = CGRectMake(0, 190+IOS5HEIGHT, 320, 200);
        submitButton.frame = CGRectMake(267, 165+IOS5HEIGHT, 48, 25);
        cancelButton.frame = CGRectMake(7, 165+IOS5HEIGHT, 48, 25);
        tiaoImageView.frame = CGRectMake(0, 162+IOS5HEIGHT, 320, 37);
    }
    [UIView commitAnimations];
    [typePickerView setHidden:NO];
    //显示确定和取消按钮的横条
    [submitButton setHidden:NO];
    [cancelButton setHidden:NO];
    [tiaoImageView setHidden:NO];
 
}

//显示营业时间选取器
-(void) showShopHoursPickerView {
    [self addShopHoursPickerView];
    //将所有选取器和横条都隐藏
    [self hiddenPickerView];
    //显示营业时间选取器
    [UIView beginAnimations: @"Animation" context:nil];
    [UIView setAnimationDuration:0.3];
    if(SSiphoneType==0){
    shopHoursPickerView.frame = CGRectMake(0, 190, 320, 200);
    submitButton.frame = CGRectMake(267, 165, 48, 25);
    cancelButton.frame = CGRectMake(7, 165, 48, 25);
    tiaoImageView.frame = CGRectMake(0, 162, 320, 37);
    }
    if(SSiphoneType==1){
        shopHoursPickerView.frame = CGRectMake(0, 190+IOS5HEIGHT, 320, 200);
        submitButton.frame = CGRectMake(267, 165+IOS5HEIGHT, 48, 25);
        cancelButton.frame = CGRectMake(7, 165+IOS5HEIGHT, 48, 25);
        tiaoImageView.frame = CGRectMake(0, 162+IOS5HEIGHT, 320, 37);
    }
    [UIView commitAnimations];
    [shopHoursPickerView setHidden:NO];
    //显示确定和取消按钮的横条
    [submitButton setHidden:NO];
    [cancelButton setHidden:NO];
    [tiaoImageView setHidden:NO];

}

//隐藏全部选取器
-(void) hiddenPickerView {
    //隐藏确定和取消按钮的横条
    [submitButton setHidden:YES];
    [cancelButton setHidden:YES];
    [tiaoImageView setHidden:YES];
    [UIView beginAnimations: @"Animation" context:nil];
    [UIView setAnimationDuration:0.3]; 

    submitButton.frame = CGRectMake(261, 428, 48, 28);
    cancelButton.frame = CGRectMake(7, 428, 48, 28);
    tiaoImageView.frame = CGRectMake(0, 423, 320, 37);
    addressPickerView.frame = CGRectMake(0, 460, 320, 460);
    typePickerView.frame = CGRectMake(0, 460, 320, 460);
    shopHoursPickerView.frame = CGRectMake(0, 460, 320, 460);
    [UIView commitAnimations];
}


//点击显示选取器
- (IBAction)showPickerViewAction:(id)sender {
    NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
    SystemSoundID system_sound_id;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
    AudioServicesPlaySystemSound(system_sound_id);
    
    //取得按钮tag
    NSInteger type=[sender tag];    
    if(type==addressTag)
    {
        usingPickerView = @"addressPicker";
        addBtn.enabled=NO;
        timeBtn.enabled=YES;
        typeBtn.enabled=YES;
        [self showAddressPickerView];
    }
    else if(type==typeTag)
    {
        usingPickerView = @"typePicker";
        addBtn.enabled=YES;
        typeBtn.enabled=NO;
        timeBtn.enabled=YES;
        [self showTypePickerView];
    }
    else
    {
        usingPickerView = @"shopHoursPicker";
        addBtn.enabled=YES;
        typeBtn.enabled=YES;
        timeBtn.enabled=NO;
        [self showShopHoursPickerView];
    }
}

//返回每个组件上的行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if(pickerView==addressPickerView)
    {
        return [addressTestData count];
    }
    else if(pickerView==typePickerView) 
    {
        return [typeTestData count];
    }
    else
    {
        return [shopHoursTestData count];
    }
}

//返回有pickerview的组件数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

////pickerview的值
//- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
//    if(pickerView==addressPickerView)
//    {
//        return [addressTestData objectAtIndex:row];
//    }
//    else if(pickerView==typePickerView)
//    {
//        return [typeTestData objectAtIndex:row];
//    }
//    else
//    {
//        return [shopHoursTestData objectAtIndex:row];
//    }
//}

////当你选中pickerview的某行时会调用该函数。
//- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
//{
//    
//    
//}
//自定义pickerview使内容显示在每行的中间，默认显示在每行的左边（(NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component）
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel *contentLbl = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 100, 30)];  
    if(pickerView==addressPickerView)
    {
        contentLbl.textAlignment = UITextAlignmentCenter;
        contentLbl.font = [UIFont systemFontOfSize:16];
        contentLbl.text=[addressTestData objectAtIndex:row];
        contentLbl.backgroundColor = [UIColor clearColor];
        
    }
    else if(pickerView==typePickerView)
    {

        contentLbl.textAlignment = UITextAlignmentCenter;
        contentLbl.font = [UIFont systemFontOfSize:16];
        contentLbl.text=[typeTestData objectAtIndex:row];
        contentLbl.backgroundColor = [UIColor clearColor];
    }
    else
    {

        contentLbl.textAlignment = UITextAlignmentCenter;
        contentLbl.font = [UIFont systemFontOfSize:16];
        contentLbl.text=[shopHoursTestData objectAtIndex:row];
        contentLbl.backgroundColor = [UIColor clearColor];
    }
        return contentLbl;
    
}



//设置指定组件上每行的宽度
/*
 -(void)pickerView:(UIPickerView *)thePickerView widthForComponet:component {
 
 }
 */


- (void)viewDidUnload {
    self.manager=nil;
    self.suppliers=nil;
    self.usingPickerView=nil;
    self.addBtn=nil;
    self.typeBtn=nil;
    self.timeBtn=nil;
    self.tiaoImageView=nil;
    self.submitButton=nil;
    self.cancelButton=nil;
    self.tableViews=nil;
    self.appDelegate=nil;
    self._refreshHeaderView=nil;
    self.HUD=nil;
    self.road=nil;
    self.isSelling=nil;
    self.typePickerView=nil;
    self.addressPickerView=nil;
    self.shopHoursPickerView=nil;
    self.addressTestData=nil;
    self.shopHoursTestData=nil;
    self.typeTestData=nil;
    self.tempSupId=nil;
    self.tempSupName=nil;
    [super viewDidUnload];
}

//- (void)dealloc {
//
//}



//新刷新控件
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)addObject{
    @autoreleasepool{
    currentPage++;
//    currentPageString=[[NSString alloc]initWithFormat:@"%d",currentPage];
//    [NSString stringWithFormat: @"%d", currentPage];
    road = addBtn.titleLabel.text;
    isSelling = @"";
    if([road isEqualToString: @"周边地区"]){
        road = nil;
    }
    if([timeBtn.titleLabel.text isEqualToString: @"营业中"]){
        isSelling = @"y";
    }
    else if([timeBtn.titleLabel.text isEqualToString: @"打烊"]){
        isSelling = @"n";
    }
    else{
        isSelling = nil;
    }
    
    
    NSArray * newSuppliers = [manager getSupplier:appDelegate.supId pageIndex:currentPage road:road isSelling:isSelling];
    
        
        for(Supplier *supplier in newSuppliers){
            if([supplier.supplierName isEqualToString:@"美味快餐厅"]){
                [sSuppliers addObject:supplier];
            }
            else{
                [fSuppliers addObject:supplier];
            }
        }
        for(Supplier *supplier in fSuppliers){
            NSLog(@"订单组%@",supplier.supplierName);
        }
        
        for(Supplier *supplier in sSuppliers){
            NSLog(@"非订单组%@",supplier.supplierName);
        }
        
        
        
//    if([appDelegate status]){
        //联网
//        newSuppliers = [manager getSupplier:appDelegate.supId pageIndex:currentPage road:road isSelling:isSelling];
//        //添加到本地
//        [fmdbSupplierManager insertSupplierByCategoryId:newSuppliers supplierCategoryId:appDelegate.supId sPage:currentPageString];
//    }
//    else{
//        //离线
//        newSuppliers=[fmdbSupplierManager getSupplierByCategoryIdAndPageFromLoc:appDelegate.supId sPage:currentPageString road:road isSelling:isSelling];
//    }
    
    if(newSuppliers !=Nil) {
        suppliers = [suppliers arrayByAddingObjectsFromArray:newSuppliers];
    }
    
    }

	//回到主线程跟新界面
	[self performSelectorOnMainThread:@selector(dosomething) withObject:nil waitUntilDone:YES];
}

//此方法是开始读取数据
- (void)reloadTableViewDataSource{
    //设置tableview不可拉动
//    tableViews.scrollEnabled=NO;
    //设置tabbar不能点击
    appDelegate.rootController.tabBar.userInteractionEnabled=NO;
	_reloading = YES;
	//打开线程
	[NSThread detachNewThreadSelector:@selector(addObject) toTarget:self withObject:nil];
}

//更改refreshHeaderView位置
-(void)dosomething
{
	int count=[suppliers count];
	if(64*count>320)
	{
		tableViews.contentSize=CGSizeMake(320, 64*count);
		_refreshHeaderView.frame=CGRectMake(0, tableViews.contentSize.height, 320, 250);
	}

    [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:0];
    	[tableViews reloadData];
}

//此方法是结束读取数据
- (void)doneLoadingTableViewData{
    NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
    SystemSoundID system_sound_id;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
    AudioServicesPlaySystemSound(system_sound_id);
    
//    tableViews.scrollEnabled=YES;
    appDelegate.rootController.tabBar.userInteractionEnabled=YES;
	_reloading = NO;
	[_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:tableViews];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{	
	[_refreshHeaderView egoRefreshScrollViewDidScroll:tableViews];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	[_refreshHeaderView egoRefreshScrollViewDidEndDragging:tableViews];
}

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
	[self reloadTableViewDataSource];
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
	return _reloading;
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
	return [NSDate date];
}

//离开页面的时候
- (void)viewDidDisappear:(BOOL)animated{
    addBtn.enabled=YES;
    typeBtn.enabled=YES;
    timeBtn.enabled=YES;
//    //还原按钮类型内容
//    [addBtn setTitle:@"周边地区" forState:UIControlStateNormal];
//    [typeBtn setTitle:@"类型" forState:UIControlStateNormal];
//    [timeBtn setTitle:@"营业情况" forState:UIControlStateNormal];
//    //还原pickerview选中内容
//    [addressPickerView selectRow:0 inComponent:0 animated:NO];
//    [typePickerView selectRow:0 inComponent:0 animated:NO];
//    [shopHoursPickerView selectRow:0 inComponent:0 animated:NO];
}

@end
